<?php

declare(strict_types=1);

namespace App\Controller\store;

use App\Constants\Agent;
use App\Constants\Business;
use App\Middleware\User\StoreMiddleware;
use App\Request\Store\Partner\CreationRequest;
use App\Service\Store\PartnerService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;

/**
 * 后台合作商控制器
 * @AutoController()
 * @Middleware(StoreMiddleware::class)
 * @author 陈奕文
 * @package App\Controller\store
 */
class PartnerController extends Controller
{

    /**
     * 合作商服务
     * @Inject()
     * @var PartnerService
     */
    private $partner_service;

    /**
     * 市场合伙人搜索
     */
    public function marketerSearch()
    {
        $params = $this->request->all();

        $partner_list = $this->partner_service->getMarketer($params);

        $this->success($partner_list);
    }

    /**
     * 市场合伙人通过-单条
     */
    public function onePass()
    {
        $id = (int)$this->request->input('id', 0);
        0 === $id && $this->error();
        $first = $this->partner_service->agent_dao->first($id);
        !$first && $this->error("不存在的市场合伙人");

        $result = $this->partner_service->agent_dao->updateDataById($id,[
            'status' => 1,
            'check_time' => time(),
        ]);
        !$result && $this->error("通过失败");
        $this->success("通过");
    }

    /**
     * 市场合伙人通过-多条
     */
    public function multiPass()
    {
        $ids = $this->request->input('ids',[]);
        if (!is_array($ids) || count($ids) <= 0) {
            $this->error("不是数组或者为空数组");
        }
        foreach ($ids as $id) {
            !is_numeric($id) && $this->error("存在非整数");
        }
        $exists = $this->partner_service->agent_dao->checkAgentsExistByIds($ids);
        !$exists && $this->error("不存在代理商");

        $result = $this->partner_service->agent_dao->updateDataByIds($ids, [
            'status' => 1,
            'check_time' => time(),
        ]);
        !$result && $this->error("通过失败");
        $this->success($result);
    }

    /**
     * 市场合伙人拒绝-单条
     */
    public function oneRejected()
    {
        $id = (int)$this->request->input('id', 0);
        0 === $id && $this->error();
        $first = $this->partner_service->agent_dao->first($id);
        !$first && $this->error("不存在的市场合伙人");

        $refuse_reason = $this->request->input('refuse_reason', '');
        $result = $this->partner_service->agent_dao->updateDataById($id,[
            'status' => 3,
            'refuse_reason' => $refuse_reason,
            'check_time' => time(),
        ]);
        !$result && $this->error("驳回失败");
        $this->success("驳回");

    }

    /**
     * 市场合伙人拒绝-多条
     */
    public function multiRejected()
    {
        $ids = $this->request->input('ids',[]);
        if (!is_array($ids) || count($ids) <= 0) {
            $this->error("不是数组或者为空数组");
        }
        foreach ($ids as $id) {
            !is_numeric($id) && $this->error("存在非整数");
        }
        $exists = $this->partner_service->agent_dao->checkAgentsExistByIds($ids);
        !$exists && $this->error("不存在代理商");

        $refuse_reason = $this->request->input('refuse_reason', '');
        $result = $this->partner_service->agent_dao->updateDataByIds($ids, [
            'status' => 3,
            'refuse_reason' => $refuse_reason,
            'check_time' => time(),
        ]);
        !$result && $this->error("驳回失败");
        $this->success($result);

    }

    /**
     * 市场合伙人多条-删除
     */
    public function multiDelete()
    {
        $ids = $this->request->input('ids',[]);
        if (!is_array($ids) || count($ids) <= 0) {
            $this->error("不是数组或者为空数组");
        }
        foreach ($ids as $id) {
            !is_numeric($id) && $this->error("存在非整数");
        }

        $exists = $this->partner_service->agent_dao->checkAgentsExistByIds($ids);
        !$exists && $this->error("代理商不存在");

        $result = $this->partner_service->agent_dao->deleteByIds($ids);
        !$result && $this->error("删除失败");

        $this->success($result);

    }

    /**
     * 查看合伙人审核详情
     */
    public function details()
    {
        $id = (int)$this->request->input('id', 0);
        0 === $id && $this->error();

        $detail = $this->partner_service->marketerDetail($id);

        $this->success($detail);

    }

    /**
     * 代理商搜索(分公司，合伙人，市代理，区代理)
     */
    public function search()
    {
        $params = $this->request->all();
        $agent_list = $this->partner_service->agentSearch($params);

        $this->success($agent_list);
    }

    /**
     * 渠道商搜索
     */
    public function channelSearch()
    {
        $params = $this->request->all();

        $channel_list = $this->partner_service->getChannelSearch($params);

        $this->success($channel_list);
    }

    /**
     * 创建分公司/市代理/区代理
     * @param CreationRequest $request
     */
    public function creation(CreationRequest $request)
    {
        $params = $request->all();

        $this->partner_service->createAgent($params);

        $this->success();
    }

    /**
     * 合作商管理-渠道商禁止
     */
    public function forbiddenChannel()
    {
        $id = (int)$this->request->input("id");
        !$id && $this->error();
        $result = $this->partner_service->user_dao->updateUserById($id,[
            'status' => 0
        ]);
        !$result && $this->error("禁用失败");
        $this->success($result);
    }


    /**
     * 合作商管理-渠道商开启
     */
    public function upChannel()
    {
        $id = (int)$this->request->input("id");
        !$id && $this->error();
        $result = $this->partner_service->user_dao->updateUserById($id,[
            'status' => 1
        ]);
        !$result && $this->error("开启正常状态失败");
        $this->success($result);
    }

    /**
     * 获得某个分公司/合伙人/市代理/区代理的详细信息
     */
    public function agentAllDetail()
    {
        $id = (int)$this->request->input("id");
        !$id && $this->error();
        $first = $this->partner_service->agent_dao->first($id);
        !$first && $this->error("不存在的代理商");
        $first = $first->makeHidden(['login_pwd', 'safe_pwd'])->toArray();

        $location_name = "";
        $location =  $this->partner_service->location_dao->getLocationByPid([
            'pid' => (int)$first['location_id'],
        ]);
        $location && $location = $location->toArray() && $location_name = $location['name'];

        $parent = $this->partner_service->agent_dao->first($first['inviter_id'], false); // 邀请人信息
        $parent_name = "";
        $parent_identity = "";
        if ($parent) {
            $parent = $parent->toArray();
            $parent_name .= $parent['name']; // 上级名称
            $parent_identity .= $parent['identity']; // 上级身份
        }

        $money_values = $this->partner_service->part_servant_config_dao->many([
            'name' =>['in',['partner_area_money', 'partner_city_money', 'partner_channel_money']]
        ], ['name', 'value'])->pluck('value', 'name')->toArray(); // 获取分佣比率配置信息

        empty($first['area_agent_money']) && $first['area_agent_money'] = $money_values['partner_area_money']; // 区代理金额返佣
        empty($first['city_agent_money']) && $first['city_agent_money'] = $money_values['partner_city_money']; // 市代理金额返佣
        empty($first['channel_agent_money']) && $first['channel_agent_money'] = $money_values['partner_channel_money']; // 渠道商金额返佣

        $first['parent_name'] = $parent_name;
        $first['parent_identity'] = $parent_identity;
        $first['location_name'] = $location_name; // 代理区域
        $this->success($first);
    }

    /**
     * 获取渠道商用户的详情
     */
    public function channelDetail()
    {
        $id = (int)$this->request->input("id");
        !$id && $this->error();

        $first = $this->partner_service->channelDetail($id);

        $this->success($first);
    }

    /**
     * 渠道商旗下分享会员
     */
    public function channelShareUser()
    {
        $id = (int)$this->request->input("id");
        !$id && $this->error();

        $select = ['id','created_at','name','phone','province', 'province_id', 'city_id', 'city','district_id',
            'district','identity_code','parent_id','group_id','integral', 'status'];
        $page_size = 10;
        $users = $this->partner_service->user_dao->getUsersByMap([
            'parent_id' => $id,
            'group_id' => 1, // 会员
        ], 'created_at desc', $select, $page_size);
        $users = $users->toArray();
        $this->success($users);
    }

    /**
     * 获取商家信息列表
     */
    public function businesses()
    {
        $params = $this->request->all();

        $business_list = $this->partner_service->getBusinessList($params);

        $this->success($business_list);
    }

    /**
     * 渠道商设置为会员
     */
    public function channelToMember()
    {
        $id = (int)$this->request->input("id");
        !$id && $this->error();

        $channel = $this->partner_service->user_dao->first($id, false);
        !$channel && $this->error("渠道商不存在");
        $channel->group_id != 2 && $this->error("该用户不是渠道商");
        $channel->group_id = 1; // 设置为会员
        $result  = $channel->save();
        !$result && $this->error("设置失败");
        $this->success($result);
    }

    /**
     * 代理商(分公司/市代/区代)重置密码
     */
    public function reset()
    {
        $id = (int)$this->request->input("id");
        !$id && $this->error();
        $agent = $this->partner_service->agent_dao->map([
            'id' => $id,
        ], false);
        !$agent && $this->error("代理商不存在");
        $agent->login_pwd = password_hash($agent->phone, PASSWORD_DEFAULT);
        $result = $agent->save();
        !$result && $this->error("重置密码失败");
        $this->success($result);
    }

    /**
     * 代理商(分公司/市代/区代)分润设置
     */
    public function profit()
    {
        $id = (int)$this->request->input("id");
        !$id && $this->error();

        $agent = $this->partner_service->agent_dao->map([
            'id' => $id,
        ], false);
        !$agent && $this->error("代理商不存在");

        $params = $this->request->all();
        if (isset($params['area_agent_money']) && !empty($params['area_agent_money'])) {
            $params['area_agent_money'] > 0.041 && $this->error("金额返佣超过数值");
            $agent->area_agent_money = (float)$params['area_agent_money']; // 区代理金额返佣
        }
        if ( isset($params['city_agent_money']) && !empty($params['city_agent_money']) )  {
            $params['city_agent_money'] > 0.041 && $this->error("金额返佣超过数值");
            $agent->city_agent_money = (float)$params['city_agent_money']; // 市代理金额返佣
        }

        if ( isset($params['channel_agent_money']) && !empty($params['channel_agent_money']) ) {
            $params['channel_agent_money'] > 0.6 && $this->error("渠道商返佣超过数值");
            $agent->channel_agent_money = (float)$params['channel_agent_money']; // 渠道商金额返佣
        }
        $result = $agent->save();
        !$result && $this->error("保存失败");
        $this->success($result);
    }

    /**
     * 代理商状态正常和启用更改
     */
    public function agentStatus()
    {
        $id = (int)$this->request->input("id");
        !$id && $this->error();

        $agent = $this->partner_service->agent_dao->map([
            'id' => $id,
        ], false);
        !$agent && $this->error("代理商不存在");

        switch ($agent->status) {
            case Agent::WAIT_CHECK: // 未审核
                $this->error("该账号未审核");
                break;
            case Agent::CHECKED: // 已审核(正常)
                $agent->status = Agent::STOPPED; // 改为禁止
                break;
            case Agent::STOPPED: // 已停用(禁止)
                $agent->status = Agent::CHECKED; // 改为正常
                break;
            case Agent::REFUSED: // 已拒绝
                $this->error("该账号已拒绝");
                break;
            default:
                $this->error("该账号状态异常");
                break;
        }
        $result = $agent->save();
        !$result && $this->error("代理商状态更改失败");
        $this->success(['status' => (int)$agent->status]);

    }

    /**
     * 商家状态的正常和启用更改
     */
    public function bizStatus()
    {
        $id = (int)$this->request->input("id");
        !$id && $this->error();

        $business = $this->partner_service->business_dao->first([
            'id' => $id,
        ]);
        !$business && $this->error("该商家不存在");

        switch ($business->status) {
            case Business::DISABLE: // 禁用
                $business->status = Business::NORMAL; // 转为正常
                break;
            case Business::NORMAL: // 正常
                $business->status = Business::DISABLE; // 转为禁用
                break;
            case Business::VERIFY_WAIT:
                $this->error("该商家待审核");
                break;
            case Business::VERIFY_FAIL:
                $this->error("该商家审核未通过");
                break;
            default:
                $this->error("该商家状态异常");
                break;
        }

        $result = $business->save();
        !$result && $this->error("商家更改状态失败");
        $this->success(['status' => (int)$business->status]);

    }

    /**
     * 代理商删除
     */
    public function agentDel()
    {
        $id = (int)$this->request->input("id");
        !$id && $this->error();
        $agent = $this->partner_service->agent_dao->map([
            'id' => $id,
        ], false);
        !$agent && $this->error("代理商不存在");

        $agent->identity == 4 && $this->error("市场合伙人不删除");

        $result = $agent->delete();
        !$result && $this->error("删除失败");
        $this->success($result);
    }

    /**
     * 商家删除
     */
    public function bizDel()
    {
        $id = (int)$this->request->input("id");
        !$id && $this->error();

        $business = $this->partner_service->business_dao->first([
            'id' => $id,
        ]);
        !$business && $this->error("该商家不存在");

        $result = $business->delete();
        !$result && $this->error("删除失败");
        $this->success($result);
    }


}
